import React, { Component } from 'react';
import { Form, Button, Modal, Spin, Input, Select, message, TreeSelect } from 'antd';
import AxiosUtil from "@/tool/AxiosUtil";

const { Option } = Select;


/**
 * 新建生成器
 *
 * @author zhangby
 * @date 18/2/20 12:12 pm
 */
// eslint-disable-next-line react/prefer-stateless-function
class CreatorEdit extends Component {
  state={
    visible: false,
    loading: false,
    tableData: [],
    fileTypeData: [],
    outPutDir: ["","/src/main/java"],
  }

  // 初始化
  editInit(){
    this.props.form.resetFields();
    const { setFieldsValue } = this.props.form;
    this.setState({ loading: true })
    // 查询
    AxiosUtil.get(`/api/creator/${this.props.creatorId}`).then(res => {
      const { result } = res;
      setFieldsValue({
        name: result.name,
        author: result.author,
        tableName: result.tableName.split(","),
        packageDir: result.packageDir,
        baseEntity: result.baseEntity,
        tablePrefix: result.tablePrefix,
        createFile: result.createFile.split(","),
      })
      const outPutDir = result.outPutDir.split(",");
      if (outPutDir.length < 2) {
        outPutDir.splice(0, 0, '');
      }
      this.setState({
        loading: false,
        outPutDir,
      })
    }).catch(() => this.setState({ loading: false }));
    // 查询文件类型
    AxiosUtil.get('/api/creator/file/type/data').then(res => {
      this.setState({ fileTypeData: res.result });
    })
    // 查询数据库
    AxiosUtil.get('/api/datasource/table/get').then(res => {
      this.setState({
        loading: false,
        tableData: res.result,
      })
    })
    this.handleOpen();
  }

  // 提交
  // eslint-disable-next-line react/sort-comp,@typescript-eslint/no-unused-vars
  handleSubmit = e => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      // eslint-disable-next-line no-empty
      if (!err) {
        const { outPutDir } = this.state;
        values["outPutDir"] = outPutDir.join("");
        values["tableName"] = values.tableName.join(",");
        values["createFile"] = values.createFile.join(",");
        // 保存
        this.setState({ loading: true });
        AxiosUtil.put(`/api/creator/${this.props.creatorId}`,values).then(() => {
          message.success("编辑代码生成器成功");
          this.setState({
            loading: false,
          })
          this.props.queryCreatorList();
          this.handleCancel();
        }).catch(() => this.setState({ loading: false }));
      }
    });
  };

  setOutPutDir(key,_this){
    const { outPutDir } = this.state;
    outPutDir[key] = _this.target.value;
    this.setState({ outPutDir })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    return (
      <span>
        {/* eslint-disable-next-line react/jsx-no-bind */}
        <span style={{ cursor: 'pointer' }} onClick={this.editInit.bind(this)}>
          {
            this.props.children !== undefined?
              this.props.children
            : <Button type="primary" shape="circle" icon="edit" />
          }
        </span>
        {/* 弹出层 */}
        <Modal
          title="编辑代码生成器"
          visible={this.state.visible}
          onOk={this.handleSubmit}
          onCancel={this.handleCancel}
          confirmLoading={this.state.loading}
          width={660}
        >
          <Spin spinning={this.state.loading} >
            <Form {...formItemLayout}>
              <Form.Item label="标签名">
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '请输入标签名',
                    },
                  ],
                })(<Input />)}
              </Form.Item>
              <Form.Item label="操作人">
                {getFieldDecorator('author', {
                  rules: [
                    {
                      required: true,
                      message: '请输入操作人',
                    },
                  ],
                })(<Input />)}
              </Form.Item>
              <Form.Item label="数据库表">
                {getFieldDecorator('tableName', {
                  rules: [
                    {
                      required: true,
                      message: '请选择数据库表',
                    },
                  ],
                })(
                  <Select mode="multiple" placeholder="数据库表" allowClear>
                    {
                      this.state.tableData.map((item, key) => (
                        <Option value={item.table} key={key}>{item.table} （ {item.description} ）</Option>
                      ))
                    }
                  </Select>
                )}
              </Form.Item>
              <Form.Item label="生成文件">
                {getFieldDecorator('createFile', {
                  initialValue: ['ENTITY','CONTROLLER','SERVICE','SERVICE_IMPL','MAPPER','OTHER'],
                  rules: [
                    {
                      required: true,
                      message: '请选择生成文件',
                    },
                  ],
                })(
                  <TreeSelect
                    allowClear
                    placeholder="生成文件"
                    treeCheckable
                    treeDefaultExpandedKeys={["0"]}
                    treeDefaultExpandAll
                    dropdownStyle={{ maxHeight: 350 }}
                    treeData={this.state.fileTypeData}
                  />
                )}
              </Form.Item>
              <Form.Item label="文件输出路径">
                <Input.Group compact>
                  {/* eslint-disable-next-line react/jsx-no-bind */}
                  <Input style={{ width: 152 }} placeholder="默认为空" value={this.state.outPutDir[0]} onChange={this.setOutPutDir.bind(this,0)}/>
                  {/* eslint-disable-next-line react/jsx-no-bind */}
                  <Input style={{ width: 152 }} value={this.state.outPutDir[1]} onChange={this.setOutPutDir.bind(this,1)} />
                </Input.Group>
              </Form.Item>
              <div style={{position: 'relative', top: -20, marginLeft: 180, fontSize: 12, color: '#9E9E9E',}}>文件输出路径，如需更改请填写，否则默认为空</div>
              <Form.Item label="包名">
                {getFieldDecorator('packageDir', {
                  rules: [
                    {
                      required: true,
                      message: '请输入包名',
                    },
                  ],
                })(<Input />)}
              </Form.Item>
              <Form.Item label="基础类">
                {getFieldDecorator('baseEntity', {})(<Input />)}
              </Form.Item>
              <Form.Item label="前缀">
                {getFieldDecorator('tablePrefix', {})(<Input />)}
              </Form.Item>
              <div style={{position: 'relative', top: -20, marginLeft: 180, fontSize: 12, color: '#9E9E9E',}}>多个前缀用逗号间隔：sys_ </div>
            </Form>
          </Spin>
        </Modal>
      </span>
    )
  }

  // eslint-disable-next-line react/sort-comp,@typescript-eslint/no-unused-vars
  handleOpen = e => {
    this.setState({ visible: true });
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  handleCancel = e => {
    this.setState({ visible: false });
  };
}

export default Form.create({name: 'CreatorEdit',})(CreatorEdit);
